package com.rybbaby.tss.core.interceptors;

import java.beans.PropertyEditorSupport;
import java.text.ParseException;
import java.text.SimpleDateFormat;

import com.rybbaby.tss.core.consts.CommonConsts;
import org.springframework.util.StringUtils;

/**
 * @description 处理时间格式
 * 
 * @author 谢进伟
 * 
 * @createDate 2016-1-25 下午11:39:54
 */
public class DateConvertEditor extends PropertyEditorSupport {
	
	private SimpleDateFormat datetimeFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
	private SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
	
	public void setAsText(String text) throws IllegalArgumentException {
		if(StringUtils.hasText(text)) {
			try {
				if(text.matches(CommonConsts.SHORTDATEREGEX)) {
					setValue(this.dateFormat.parse(text));
				} else if(text.matches(CommonConsts.LONGDATEREGEX)) {
					setValue(this.datetimeFormat.parse(text));
				} else if(text.matches(CommonConsts.DATETIMEREGEX)) {
					text = text.replace(".0" , "");
					setValue(this.datetimeFormat.parse(text));
				} else {
					throw new IllegalArgumentException("Could not parse date, date format is error ");
				}
			} catch (ParseException ex) {
				IllegalArgumentException iae = new IllegalArgumentException("Could not parse date: " + ex.getMessage());
				iae.initCause(ex);
				throw iae;
			}
		} else {
			setValue(null);
		}
	}
	
}
